package com.tao.interceptor;

import com.tao.context.UserContext;
import com.tao.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    JWTUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        String jwt = request.getHeader(jwtUtil.getTokenName());
        try {
            log.info("拦截器工作啦！！！！！");
            Claims claims= jwtUtil.parseJWT(jwt);
            Integer id = claims.get("id", Integer.class);
            Integer roleId=claims.get("roleId",Integer.class);

            UserContext.setThreadUserId(id);
            log.info("放入线程的用户id：{}",id);

            UserContext.setThreadUserRoleId(roleId);
            log.info("放入线程的用户roleId：{}",roleId);

            log.info("成功解析令牌内容：{}",claims);
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear();
    }
}
